package org.ricks.net.action.protocol;

import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.context.head.DefInnerHeadMeta;
import org.ricks.net.action.context.head.HeadMeta;
import org.ricks.net.action.context.session.TcpSessionAdapter;
import org.ricks.net.action.parser.ProtocolParser;
import org.ricks.net.action.context.head.RpcHeadMeta;
import org.ricks.net.extension.protocol.FixedLengthBytesProtocol;
import org.ricks.net.transport.AioSession;
import java.nio.ByteBuffer;

public class DefInnerProtocol extends FixedLengthBytesProtocol<FlowContext<? extends HeadMeta>> {
    public final ProtocolParser parser;

    public DefInnerProtocol(ProtocolParser parser) {
        this.parser = parser;
    }

    @Override
    protected FlowContext<? extends HeadMeta> decode(byte[] bytes, AioSession session) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        byte mark = byteBuffer.get();
        short cmd = byteBuffer.getShort();

        if ((mark & HeadMeta.FLAG_RPC) != 0) {
            int msgId = byteBuffer.getInt();
            byte[] data = new byte[byteBuffer.remaining()];
            byteBuffer.get(data);

            // 修复：正确解析所有标志位
            boolean isResponse = (mark & HeadMeta.FLAG_RESPONSE) != 0;
            boolean isHeartbeat = (mark & HeadMeta.FLAG_HEARTBEAT) != 0;

            RpcHeadMeta headMeta = new RpcHeadMeta(cmd, isResponse, isHeartbeat, msgId);
            return new FlowContext<>(new TcpSessionAdapter(session, parser), headMeta, data, parser);
        } else {
            byte[] data = new byte[byteBuffer.remaining()];
            byteBuffer.get(data);
            // 修复：使用正确的cmd值
            DefInnerHeadMeta headMeta = new DefInnerHeadMeta(mark, cmd);
            return new FlowContext<>(new TcpSessionAdapter(session, parser), headMeta, data, parser);
        }
    }
}
